/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.report.web;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sys.utils.WeChatTokenUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.report.entity.WeekReport;
import com.jeeplus.modules.report.service.WeekReportService;

/**
 * 周报Controller
 * @author 卢经纬
 * @version 2018-06-27
 */
@Controller
@RequestMapping(value = "${adminPath}/report/weekReport")
public class WeekReportController extends BaseController {

	@Autowired
	private WeekReportService weekReportService;
	@Autowired
	private OfficeService officeService;
	
	@ModelAttribute
	public WeekReport get(@RequestParam(required=false) String id) {
		WeekReport entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = weekReportService.get(id);
		}
		if (entity == null){
			entity = new WeekReport();
		}
		return entity;
	}
	
	/**
	 * 周报列表页面
	 */
	@RequiresPermissions("report:weekReport:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/report/weekReportList";
	}
	
		/**
	 * 周报列表数据
	 */
	@ResponseBody
	@RequiresPermissions("report:weekReport:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(WeekReport weekReport, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WeekReport> page = weekReportService.findPage(new Page<WeekReport>(request, response), weekReport); 
		return getBootstrapData(page);
	}


	/**
	 * 微信端查看，增加，编辑周报表单页面
	 */
	@RequestMapping(value = "/weChatAdd")
	public String weChatAdd(WeekReport weekReport, Model model) {
		return "modules/report/weekReportWeChatAdd";
	}
	/**
	 * 微信端保存周报
	 */
	@RequiresPermissions(value={"report:weekReport:add","report:weekReport:edit"},logical=Logical.OR)
	@RequestMapping(value = "weChatTemp")
	public String weChatTemp(WeekReport weekReport, Model model, RedirectAttributes redirectAttributes) throws Exception{
		//设置暂存类型
		weekReport.setType("0");
		if (!beanValidator(model, weekReport)){
			return form(weekReport, model);
		}
		if(!weekReport.getIsNewRecord()){//编辑表单保存
			WeekReport t = weekReportService.get(weekReport.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(weekReport, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			weekReportService.save(t);//保存
		}else{//新增表单保存
			weekReportService.save(weekReport);//保存
		}
		addMessage(redirectAttributes, "暂存周报成功");
		return "redirect:"+Global.getAdminPath()+"/report/weekReport/weChatAdd?repage";
	}

	/**
	 * 微信端周报表单页面
	 *
	 */
	@ResponseBody
	@RequiresPermissions(value={"report:weekReport:view","report:weekReport:add","report:weekReport:edit"},logical=Logical.OR)
	@RequestMapping(value = "weChatForm")
	public String weChatForm(HttpServletResponse response,WeekReport weekReport, Model model) {
		AjaxJson j = new AjaxJson();
		j.setSuccess(true);
		weekReport = weekReportService.getUserTemp(UserUtils.getUser());
		j.put("weekReport",weekReport);
		if(weekReport.getIsNewRecord()){//如果ID是空为添加
			j.put("isAdd", true);
		}
		return renderString(response, j.getJsonStr());
	}

	/**
	 * 微信端周报列表页面
	 */
	@RequestMapping(value = {"/weChatList"})
	public String weChatList(WeekReport weekReport, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<WeekReport> list = weekReportService.findList(weekReport);
		model.addAttribute("list", list);
		return "modules/report/weekReportWeChatList";
	}

	/**
	 * 微信端保存周报
	 */
	@RequiresPermissions(value={"report:weekReport:add","report:weekReport:edit"},logical=Logical.OR)
	@RequestMapping(value = "weChatSave")
	@ResponseBody
	public String weChatSave(HttpServletResponse response,WeekReport weekReport, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, weekReport)){
			return form(weekReport, model);
		}
		if(!weekReport.getIsNewRecord()){//编辑表单保存
			WeekReport t = weekReportService.get(weekReport.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(weekReport, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			weekReportService.save(t);//保存
		}else{//新增表单保存
			if(weekReport.getType().equals("1")){
				StringBuffer touser = new StringBuffer();
				//推送给部门负责人
				User user = UserUtils.getUser();
				String[] offId = user.getOffice().getParentIds().split(",");
				List<Office> offices = new ArrayList<Office>();
				for (int i = 0; i <= offId.length; i++) {
					if (i == offId.length) {
						Office office = officeService.get(user.getOffice().getId());
						offices.add(office);
					} else {
						if (!offId[i].equals("0")) {
							Office office = officeService.get(offId[i]);
							offices.add(office);
						}
					}
				}
				Set<String> set = new HashSet<String>();
				for (int i = 0; i < offices.size(); i++) {
					if (offices.get(i).getPrimaryPerson() != null) {
						set.add(offices.get(i).getPrimaryPerson().getLoginName());
					}else if(offices.get(i).getDeputyPerson() != null){
						set.add(offices.get(i).getDeputyPerson().getLoginName());
					}
				}
				Iterator<String> it = set.iterator();
				while(it.hasNext()){//判断是否有下一个
					if (touser.equals("")) {
						touser.append(it.next());
					}else{
						touser.append("|" + it.next());
					}
				}
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-hh");
				String content = "【周报"+format.format(weekReport.getStartTime())+"-"+format.format(weekReport.getEndTime())+"】"+UserUtils.getUser().getName()
						+"："+weekReport.getContent();
				WeChatTokenUtil.sendTextMsg(touser.toString(), "", "",1000004, content, 0);
			}
			weekReportService.save(weekReport);//保存
		}
		j.put("weekReport",weekReport);
		j.setSuccess(true);
		return renderString(response,j);
	}

	/**
	 * 查看，增加，编辑周报表单页面
	 */
	@RequiresPermissions(value={"report:weekReport:view","report:weekReport:add","report:weekReport:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WeekReport weekReport, Model model) {
		model.addAttribute("weekReport", weekReport);
		if(StringUtils.isBlank(weekReport.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "modules/report/weekReportForm";
	}

	/**
	 * 保存周报
	 */
	@RequiresPermissions(value={"report:weekReport:add","report:weekReport:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WeekReport weekReport, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, weekReport)){
			return form(weekReport, model);
		}
		//新增或编辑表单保存
		weekReportService.save(weekReport);//保存
		addMessage(redirectAttributes, "保存周报成功");
		return "redirect:"+Global.getAdminPath()+"/report/weekReport/?repage";
	}
	
	/**
	 * 删除周报
	 */
	@ResponseBody
	@RequiresPermissions("report:weekReport:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(WeekReport weekReport, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		weekReportService.delete(weekReport);
		j.setMsg("删除周报成功");
		return j;
	}
	
	/**
	 * 批量删除周报
	 */
	@ResponseBody
	@RequiresPermissions("report:weekReport:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			weekReportService.delete(weekReportService.get(id));
		}
		j.setMsg("删除周报成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("report:weekReport:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(WeekReport weekReport, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "周报"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WeekReport> page = weekReportService.findPage(new Page<WeekReport>(request, response, -1), weekReport);
    		new ExportExcel("周报", WeekReport.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出周报记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("report:weekReport:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WeekReport> list = ei.getDataList(WeekReport.class);
			for (WeekReport weekReport : list){
				try{
					weekReportService.save(weekReport);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条周报记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条周报记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入周报失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/report/weekReport/?repage";
    }
	
	/**
	 * 下载导入周报数据模板
	 */
	@RequiresPermissions("report:weekReport:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "周报数据导入模板.xlsx";
    		List<WeekReport> list = Lists.newArrayList(); 
    		new ExportExcel("周报数据", WeekReport.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/report/weekReport/?repage";
    }

}